import md5 from 'js-md5';
const APP_ID = 1646789515192;
const SECRET_KEY = 'wF5kW7fSLWi8On7F7eXntswHUnZPfIt6';
const SIGN_TYPE = 'MD5';

const timeStampFun = () => {
  let nowDate = new Date();
  let yy = nowDate.getFullYear();
  let mm = nowDate.getMonth() + 1;
  let dd = nowDate.getDate();
  let hh = nowDate.getHours();
  let mf = nowDate.getMinutes();
  let ms = nowDate.getSeconds();
  mm = String(mm).padStart(2, 0);
  dd = String(dd).padStart(2, 0);
  hh = String(hh).padStart(2, 0);
  mf = String(mf).padStart(2, 0);
  ms = String(ms).padStart(2, 0);
  return `${yy}${mm}${dd}${hh}${mf}${ms}`;
};

const nonceFun = () => {
  let length = 16;
  let chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  let result = '';
  for (let i = length; i > 0; --i) {
    result += chars[Math.floor(Math.random() * chars.length)];
  }
  return result;
};

const signFun = (params) => {
  let TIMESTAMP = timeStampFun();
  let NONCE = nonceFun();
  let signParam = {
    APP_ID,
    NONCE,
    TIMESTAMP,
    SIGN_TYPE
  };
  if (params) {
    signParam = {
      ...signParam,
      ...params
    };
  }
  let sortKeys = Object.keys(signParam).sort();
  let sign = sortKeys.reduce((pre, key) => {
    let value = signParam[key];
    if (value !== '' && value !== null) {
      pre += `${key}=${value}&`;
    }
    return pre;
  }, '');
  sign += `SECRET_KEY=${SECRET_KEY}`;
  let SIGN = md5(sign);
  return Object.assign({}, signParam, {
    SIGN: SIGN
  });
};
export default signFun;
